/**
 * authentication.js
 * 鉴权reducer, 用在登录视图与其他需要鉴权信息的视图
 *
 * created by qiuwei
 * version 1.0.0
 * 2016年03月07日
 */

import { CONTROL_STATE } from '../../../constants/control';
import { 
	SHOW_ERROR, 
	AUTO_AUTHENTICATE,
	AUTHENTICATE_REQUEST,
	AUTHENTICATE_SUCCESS,
	AUTHENTICATE_FAILURE,
	LOGOUT
} from '../actions/authentication';

import { merge } from 'lodash/object';
import moment from 'moment';

import * as API from '../../../constants/API';

/**
 * 本地存储键名
 * @type {String}
 */
const STORAGE_KEY = 'state';

/**
 * 初始鉴权信息页面状态
 * @type {Object}
 */
export const INITIALIZE_STATE = {
	// 提示消息
	message: '',
	// 验证码区域
	codeArea: {
		// 验证码图片地址, 需要传入手机号
		url: `${API.HOST}${API.SECURITY_CODE_ON_SERVER}?mobile=`
	},
	// 密码输错次数
	pwdErrorCount: 0,
	// 用户信息
	user: {
		/*// 用户名称
		name: '张昊波',
		// 级别: 1校, 2区县, 3城市
		right: '3',
		// 手机号
		mobile: '13811762727',
		// 初始可选范围
		item_ids: [{
			// 学校ID
			item_id: '16754',
			// 学校名称
			name: '北京二十二中',
			// 上级
			parent_id: 500,
			// 上级名称
			parent_name: 'ceshi',
			// 忽略字段
			level: 4
		}]*/
	},
	// 5天免登录
	isAutoAuthenticate: false,
	// 正在和服务器通讯
	isFetching: false
};

//*
~function(global) {
	let storage = global.sessionStorage;
	if (storage && !storage[STORAGE_KEY]) 
		storage = global.localStorage;

	let state;
	if (storage && (state = storage[STORAGE_KEY])) {
		try {
			state = JSON.parse(decodeURIComponent(atob(state)));
			state.expired = moment(state.expired);
		} catch(e) {
			return console.log(`initialize state failed from storage. reason: ${e.message}`);
		}

		if (moment.isMoment(state.expired) && moment().isBefore(state.expired)) {
			INITIALIZE_STATE.user = state.user;
		}
	}
}(window);
//*/

/**
 * 处理鉴权信息
 * @param  {Object} state  当前页面状态
 * @param  {Object} action 请求描述对象
 * @return {Object}        当前页面新状态
 */
export default function authenticate(state = INITIALIZE_STATE, action = {}) {
	let { type, ...others } = action;
	switch(type) {
		case SHOW_ERROR: 
		{
			// TODO: create new state
			//丢失焦点错误，获取错误信息
			let { errorMessage } = others.payload;
			let newState = Object.assign({}, state, { 
				message: errorMessage 
			});
			return newState;
		}
		case AUTO_AUTHENTICATE: 
			// TODO: create new state
			//五天自动登录
			{
				let { enableOrDisable } = others.payload;
				let newState = Object.assign({}, state , { 
					isAutoAuthenticate: enableOrDisable 
				});
				return newState;
			}
		case AUTHENTICATE_REQUEST: 
			// TODO: create new state
			//登陆请求
			return Object.assign({} , state, {
				isFetching:true,
				message: ''
			});
		case AUTHENTICATE_SUCCESS: 
			// TODO: create new state
			//验证用户信息成功，停止验证请求，获取用户信息
			{
				let { user } = others.payload;
				let newState = Object.assign({}, state, {
					isFetching: false,
					pwdErrorCount: 0,
					message: '',
					user
				});

				let storageState = {
					expired: moment().add(5, 'd'),
					user
				};

				if (state.isAutoAuthenticate) {
					// 如果选择了5天自动登录
					window.localStorage[STORAGE_KEY] = btoa(encodeURIComponent(JSON.stringify(storageState)));
				}
				window.sessionStorage[STORAGE_KEY] = btoa(encodeURIComponent(JSON.stringify(storageState)));

				return newState
			}	
		case AUTHENTICATE_FAILURE: 
			// TODO: create new state
			//验证用户信息失败，停止请求验证，获取错误消息
			{
				let { errorMessage } = others.payload;
				let newState = Object.assign({}, state ,{
					isFetching:false,
					pwdErrorCount: state.pwdErrorCount + 1,
					message:errorMessage
					});
				return newState;
			}
		case LOGOUT:
			// 用户注销
			window.localStorage.removeItem(STORAGE_KEY);
			window.sessionStorage.removeItem(STORAGE_KEY);

			return Object.assign({}, state, { user: {} })
		default: 
			return state;
	}
};